package com.billionsfinance.hessian.core;


import com.billionsfinance.hessian.common.anno.HessianPath;
import com.billionsfinance.hessian.mapper.ClientInfoMapper;
import com.billionsfinance.hessian.model.ClientInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.ibatis.session.SqlSession;
import org.reflections.Reflections;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @ ClassName: HessianClientInitFactory.java
 * @ Author: WeiHui-Z
 * @ Date: 2016/11/23 14:03
 * @ Version: v1.0.0
 */
public class HessianClientInitFactory extends HessianInitFactory {

    /**
     * Hessian服务端访问url地址
     */
    private String hessianUrl;

    public void setHessianUrl(String hessianUrl) {
        this.hessianUrl = hessianUrl;
    }

    @Override
    protected void initHessianData() {
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            ClientInfoMapper mapper = sqlSession.getMapper(ClientInfoMapper.class);
            if (autoInsert) {
                mapper.deleteAll();
                sqlSession.commit(true);
                autoInsertHessianData(mapper);
                sqlSession.commit(true);
            }
            loadToMemory(mapper.findAll());
        }
    }

    private void autoInsertHessianData(ClientInfoMapper mapper) {
        StopWatch watch = new StopWatch();
        watch.start();
        if (servicePackages == null) {
            throw new IllegalArgumentException("Hessian客户端，Hessian接口包名 servicePackages 尚未配置。");
        }
        LOGGER.info("初始化Hessian信息到数据库开始！扫描包路径:{}", Arrays.asList(servicePackages));
        Reflections reflections = new Reflections(servicePackages);
        Set<Class<?>> hessianClasses = reflections.getTypesAnnotatedWith(HessianPath.class);
        for (Class<?> hessianClass : hessianClasses) {
            if (hessianClass.isInterface()) {
                String simpleName = hessianClass.getSimpleName();
                String serviceClassName = hessianClass.getName();
                String accessUrl;
                if (StringUtils.endsWith(hessianUrl, "/")) {
                    accessUrl = hessianUrl + simpleName;
                } else {
                    accessUrl = hessianUrl + "/" + simpleName;
                }
                // 保存hessian服务端数据
                ClientInfo info = new ClientInfo();
                info.setAppCode(appCode);
                info.setInterfaceName(serviceClassName);
                info.setGroupNo("");
                info.setAccessUrl(accessUrl);
                info.setConnTimeout(100);
                info.setReadTimeout(200);
                info.setCreateBy(createBy);
                info.setUpdateBy(createBy);

                mapper.insert(info);
            }
        }
        watch.stop();
        LOGGER.info("初始化Hessian信息到数据库结束，耗时:{}ms,服务端表插入:{}条数据。", watch.getTime(), hessianClasses.size());
    }

    /**
     * 加载客户端信息到内存中
     *
     * @param clients 客户端信息
     */
    private void loadToMemory(List<ClientInfo> clients) {
        for (ClientInfo clientInfo : clients) {
            HessianCacheManager.setClientInfo(clientInfo);
        }
    }
}